package com.example.project.controller.project;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.project.annotation.Log;
import com.example.project.core.controller.BaseController;
import com.example.project.core.domain.AjaxResult;
import com.example.project.core.page.TableDataInfo;
import com.example.project.entity.Company;
import com.example.project.entity.Project;
import com.example.project.entity.ProjectMember;
import com.example.project.entity.User;
import com.example.project.enums.BusinessType;
import com.example.project.service.ProjectService;
import com.example.project.utils.poi.ExcelUtil;

/**
 * 项目Controller
 * 
 * @author ruoyi
 * @date 2025-09-15
 */
@Controller
@RequestMapping("/project")
public class ProjectController extends BaseController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	private String prefix = "pm/project";

	@Autowired
	private ProjectService projectService;

	@RequiresPermissions("pm:project:view")
	@GetMapping("index")
	public String index() {

		return prefix + "/project_index";
	}

	@RequiresPermissions("pm:project:add")
	@GetMapping("/addProject")
	public String addProject(ModelMap mmap) {
		List<Project> projectsList = projectService.findAllList(1);
		mmap.put("projectsList", projectsList);
		// 用户列表
		List<User> userList = userService.findAllList();
		mmap.put("userList", userList);
		return prefix + "/project_add";
	}

	/**
	 * 保存项目
	 */
	@RequiresPermissions("pm:project:add")
	@Log(title = "项目", businessType = BusinessType.INSERT)
	@PostMapping("/saveProject")
	@ResponseBody
	public AjaxResult saveProject(Project project) {
		int result = 0;
		Long id = project.getId();
		String loginName = getLoginName(); // 提取登录名，避免重复调用

		if (id != null && id != 0) {
			// 更新项目
			project.setUpdateBy(loginName);
			result = projectService.updateProject(project);
			if (result > 0) {
				handleProjectLeader(project, loginName, true); // true表示更新操作
			}
		} else {
			// 新增项目
			project.setCreateBy(loginName);
			result = projectService.insertProject(project);
			if (result > 0) {
				handleProjectLeader(project, loginName, false); // false表示插入操作
			}
		}

		// 处理业务错误码
		if (result == -2) {
			return error("标识是无效的");
		}
		if (result == -1) {
			return error("标识已经被使用");
		}
		return toAjax(result);
	}

	/**
	 * 处理项目负责人逻辑
	 * 
	 * @param project   项目对象
	 * @param loginName 当前登录用户名
	 * @param isUpdate  是否为更新操作（true需要处理旧负责人）
	 */
	private void handleProjectLeader(Project project, String loginName, boolean isUpdate) {
		Long projectLeader = project.getProjectLeader();
		if (projectLeader == null || projectLeader == 0) {
			return; // 无负责人时直接返回
		}

		if (isUpdate) {
			// 处理旧负责人：删除非新负责人的当前负责人
			ProjectMember currentLeaderQuery = new ProjectMember();
			currentLeaderQuery.setProjectId(project.getId());
			currentLeaderQuery.setRoleId(1L); // 角色ID 1表示负责人
			List<ProjectMember> currentLeaders = projectMemberService.selectProjectMemberList(currentLeaderQuery);

			for (ProjectMember currentLeader : currentLeaders) {
				if (!currentLeader.getUserId().equals(projectLeader)) {
					int deleteResult = projectMemberService.deleteProjectMemberById(currentLeader.getId());
					if (deleteResult > 0) {
						logger.info("删除原项目负责人成功，项目ID：{}，原负责人ID：{}", project.getId(), currentLeader.getUserId());
					} else {
						logger.warn("删除原项目负责人失败，项目ID：{}，原负责人ID：{}", project.getId(), currentLeader.getUserId());
					}
				}
			}
		}

		// 添加或更新新负责人
		ProjectMember queryMember = new ProjectMember();
		queryMember.setUserId(projectLeader);
		queryMember.setProjectId(project.getId());
		List<ProjectMember> existingMembers = projectMemberService.selectProjectMemberList(queryMember);

		if (existingMembers.isEmpty()) {
			// 负责人不存在于项目中，新增记录
			ProjectMember member = new ProjectMember();
			member.setUserId(projectLeader);
			member.setProjectId(project.getId());
			member.setCreateBy(loginName);
			member.setRoleId(1L);
			member.setSortOrder(1);
			int insertResult = projectMemberService.insertProjectMember(member);
			if (insertResult <= 0) {
				logger.warn("添加项目负责人失败，项目ID：{}，负责人ID：{}", project.getId(), projectLeader);
			} else {
				logger.info("成功添加项目负责人，项目ID：{}，负责人ID：{}", project.getId(), projectLeader);
			}
		} else {
			// 负责人已存在，检查角色
			ProjectMember existingMember = existingMembers.get(0);
			if (1L != existingMember.getRoleId()) { // 使用equals避免空指针
				existingMember.setRoleId(1L);
				existingMember.setSortOrder(1);
				existingMember.setUpdateBy(loginName);
				int updateResult = projectMemberService.updateProjectMember(existingMember);
				if (updateResult <= 0) {
					logger.warn("更新项目负责人角色失败，项目ID：{}，负责人ID：{}", project.getId(), projectLeader);
				} else {
					logger.info("成功更新项目负责人角色，项目ID：{}，负责人ID：{}", project.getId(), projectLeader);
				}
			} else {
				logger.info("项目负责人角色未变化，项目ID：{}，负责人ID：{}", project.getId(), projectLeader);
			}
		}
	}

	/**
	 * 修改项目
	 */
	@RequiresPermissions("pm:project:edit")
	@GetMapping("/editProject/{id}")
	public String editProject(@PathVariable("id") Long id, ModelMap mmap) {
		Project projectsInfo = projectService.selectProjectById(id);
		mmap.put("projectsInfo", projectsInfo);
		// 用户列表
		List<User> userList = userService.findAllList();
		mmap.put("userList", userList);
		return prefix + "/project_edit";
	}

	@RequiresPermissions("pm:project:view")
	@GetMapping()
	public String projects() {
		return prefix + "/project";
	}

	/**
	 * 查询项目列表
	 */
	@RequiresPermissions("pm:project:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(ModelMap mmap, Project project) {
		startPage();

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("dataScope", " order by create_time desc, state desc ");
		project.setParams(map);
		List<Project> projectsList = projectService.selectProjectList(project);
		projectsList.forEach(info -> {
			User user = commonService.getUserInfo(info.getProjectLeader());
			info.setProjectLeaderName(user != null ? user.getUserName() : info.getProjectLeader() == 1 ? "管理员" : "");
		});
		return getDataTable(projectsList);
	}

	/**
	 * 导出项目列表
	 */
	@RequiresPermissions("pm:project:export")
	@Log(title = "项目", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	@ResponseBody
	public AjaxResult export(Project tProject) {
		List<Project> list = projectService.findAllList(1);
		ExcelUtil<Project> util = new ExcelUtil<Project>(Project.class);
		return util.exportExcel(list, "项目数据");
	}

	/**
	 * 新增项目
	 */
	@RequiresPermissions("pm:project:add")
	@GetMapping("/add")
	public String add(ModelMap mmap) {
		List<Project> projectsList = projectService.findAllList(1);
		mmap.put("projectsList", projectsList);
		return prefix + "/add";
	}

	/**
	 * 新增保存项目
	 */
	@RequiresPermissions("pm:project:add")
	@Log(title = "项目", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(Project project) {
		project.setCreateBy(getLoginName());
		int insertProject = projectService.insertProject(project);
		if (insertProject == -2) {
			return error("标识是无效的");
		}
		if (insertProject == -1) {
			return error("标识已经被使用");
		}
		if (insertProject > 0) {
			Long projectLeader = project.getProjectLeader();
			// 添加成员
			if (projectLeader != null && projectLeader != 0) {
				// 用户不存在于项目中，添加为负责人
				ProjectMember member = new ProjectMember();
				member.setUserId(projectLeader);
				member.setProjectId(project.getId());
				member.setCreateBy(getLoginName());
				// 设置角色为项目负责人（假设负责人角色的ID为1）
				member.setRoleId(1L);
				// 设置排序号为1（负责人排在最前面）
				member.setSortOrder(1);

				int insertResult = projectMemberService.insertProjectMember(member);
				if (insertResult <= 0) {
					logger.warn("添加项目负责人失败，项目ID：{}，负责人ID：{}", project.getId(), projectLeader);
				} else {
					logger.info("成功添加项目负责人，项目ID：{}，负责人ID：{}", project.getId(), projectLeader);
				}
			}
		}
		return toAjax(insertProject);
	}

	/**
	 * 修改项目
	 */
	@RequiresPermissions("pm:project:edit")
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Long id, ModelMap mmap) {
		List<Project> projectsList = projectService.findAllList(1);
		mmap.put("projectsList", projectsList);
		Project tProject = projectService.selectProjectById(id);
		mmap.put("tProject", tProject);
		return prefix + "/edit";
	}

	/**
	 * 修改保存项目
	 */
	@RequiresPermissions("pm:project:edit")
	@Log(title = "项目", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(Project project) {
		project.setUpdateBy(getLoginName());

		int updateProject = projectService.updateProject(project);

		if (updateProject > 0) {
			Long projectLeader = project.getProjectLeader();
			// 添加成员
			if (projectLeader != null && projectLeader != 0) {
				// 先查询项目中当前是否有负责人（角色ID为1）
				ProjectMember currentLeaderQuery = new ProjectMember();
				currentLeaderQuery.setProjectId(project.getId());
				currentLeaderQuery.setRoleId(1L);
				List<ProjectMember> currentLeaders = projectMemberService.selectProjectMemberList(currentLeaderQuery);

				// 如果有当前负责人且不是新负责人，则删除或更新其角色
				if (!currentLeaders.isEmpty()) {
					for (ProjectMember currentLeader : currentLeaders) {
						if (!currentLeader.getUserId().equals(projectLeader)) {
							// 删除之前的负责人记录
							int deleteResult = projectMemberService.deleteProjectMemberById(currentLeader.getId());
							if (deleteResult > 0) {
								logger.info("删除原项目负责人成功，项目ID：{}，原负责人ID：{}", project.getId(), currentLeader.getUserId());
							} else {
								logger.warn("删除原项目负责人失败，项目ID：{}，原负责人ID：{}", project.getId(), currentLeader.getUserId());
							}
						}
					}
				}

				// 查询该用户在当前项目中的成员信息
				ProjectMember queryMember = new ProjectMember();
				queryMember.setUserId(projectLeader);
				queryMember.setProjectId(project.getId());
				List<ProjectMember> existingMembers = projectMemberService.selectProjectMemberList(queryMember);

				if (existingMembers.isEmpty()) {
					// 用户不存在于项目中，添加为负责人
					ProjectMember member = new ProjectMember();
					member.setUserId(projectLeader);
					member.setProjectId(project.getId());
					member.setCreateBy(getLoginName());
					// 设置角色为项目负责人（假设负责人角色的ID为1）
					member.setRoleId(1L);
					// 设置排序号为1（负责人排在最前面）
					member.setSortOrder(1);

					int insertResult = projectMemberService.insertProjectMember(member);
					if (insertResult <= 0) {
						logger.warn("添加项目负责人失败，项目ID：{}，负责人ID：{}", project.getId(), projectLeader);
					} else {
						logger.info("成功添加项目负责人，项目ID：{}，负责人ID：{}", project.getId(), projectLeader);
					}
				} else {
					// 用户已存在于项目中，检查角色是否为负责人
					ProjectMember existingMember = existingMembers.get(0);
					if (1L != existingMember.getRoleId()) {
						// 角色不同，更新为负责人角色
						existingMember.setRoleId(1L);
						existingMember.setSortOrder(1);
						existingMember.setUpdateBy(getLoginName());

						int updateResult = projectMemberService.updateProjectMember(existingMember);
						if (updateResult <= 0) {
							logger.warn("更新项目负责人角色失败，项目ID：{}，负责人ID：{}", project.getId(), projectLeader);
						} else {
							logger.info("成功更新项目负责人角色，项目ID：{}，负责人ID：{}", project.getId(), projectLeader);
						}
					} else {
						// 角色相同，跳过操作
						logger.info("项目负责人角色未变化，项目ID：{}，负责人ID：{}", project.getId(), projectLeader);
					}
				}
			}
		}
		return toAjax(updateProject);
	}

	/**
	 * 项目详情
	 */
	@RequiresPermissions("pm:project:detail")
	@GetMapping("/detail/{id}")
	public String detail(@PathVariable("id") Long projectid, ModelMap mmap) {
		try {
			Project projectsInfo = projectService.selectProjectById(projectid);
			if (projectsInfo != null) {
				mmap.put("projectsInfo", projectsInfo);
			} else {
				// 如果项目不存在，返回空对象
				mmap.put("projectsInfo", new Project());
			}

			// 公司列表
			Company company = new Company();
			company.setProjectId(projectid);
			List<Company> companieList = companyService.selectCompanyList(company);
			mmap.put("companieList", companieList != null ? companieList : new ArrayList<>());

			// 成员（数据库已经按角色排序字段排序，第一个位置的默认为负责人）
			List<ProjectMember> memberList = projectMemberService.selectProjectMemberListByProjectId(projectid);
			mmap.put("memberList", memberList != null ? memberList : new ArrayList<>());
		} catch (Exception e) {
			// 异常处理，确保数据完整性
			logger.error("获取项目详情失败，项目ID: " + projectid, e);
			mmap.put("projectsInfo", new Project());
			mmap.put("companieList", new ArrayList<>());
			mmap.put("memberList", new ArrayList<>());
		}
		return prefix + "/detail";
	}

	/**
	 * 判断是否为项目负责人
	 * 
	 * @param roleName 角色名称
	 * @return 是否为负责人
	 */
	private boolean isProjectLeader(String roleName) {
		if (roleName == null)
			return false;
		// 常见的负责人角色名称
		return roleName.contains("负责人") || roleName.contains("项目经理") || roleName.contains("主管")
				|| roleName.contains("领导") || roleName.equalsIgnoreCase("leader")
				|| roleName.equalsIgnoreCase("manager");
	}

	@GetMapping("/info/{id}")
	@ResponseBody
	public AjaxResult info(@PathVariable("id") Long id) {
		Project projectsInfo = projectService.selectProjectById(id);
		return success(projectsInfo);
	}

	/**
	 * 删除项目
	 */
	@RequiresPermissions("pm:project:remove")
	@Log(title = "项目", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
	@ResponseBody
	public AjaxResult remove(String ids) {
		return toAjax(projectService.deleteProjectByIds(ids));
	}

	/**
	 * 项目状态修改
	 */
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@RequiresPermissions("pm:project:edit")
	@PostMapping("/changeState")
	@ResponseBody
	public AjaxResult changeStatus(Project projects) {
		return toAjax(projectService.changeStatus(projects));
	}

}
